﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;


public static class XmlFileProvider
{

    public static string ToXML(this object obj)
    {

        StringWriter sw = new StringWriter(new StringBuilder());
        try
        {
            XmlSerializer x = new XmlSerializer(obj.GetType());
            x.Serialize(sw, obj);
        }
        catch { return ""; }
        return sw.ToString();
    }

    public static T FromXML<T>(string xml)
    {
        XmlSerializer x = new XmlSerializer(typeof(T));
        StringReader sr = new StringReader(xml);

        var obj = x.Deserialize(sr);
        return (T)obj;
    }

    public static void SaveToFile(this object obj, string fileloc)
    {
        File.WriteAllText(fileloc, obj.ToXML());
    }

    public static T OpenXMLObjectFile<T>(string fileloc)
    {
        return FromXML<T>(File.ReadAllText(fileloc));
    }

}

